package com.huitong.common.mybatis.interceptor;

import cn.hutool.core.collection.CollUtil;
import com.huitong.common.mybatis.encrypt.EncryptorManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Statement;
import java.util.List;

import static com.huitong.common.mybatis.encrypt.EncryptorManager.HandleType.DECRYPT;

/**
 * 出参解密拦截器
 *
 * @author fromdrowning
 * @date 2024/4/11 12:17
 */
@Slf4j
@RequiredArgsConstructor
@Intercepts(
    @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)
)
public class DecryptInterceptor implements Interceptor {

    /**
     * 敏感字段加密算法管理器
     */
    private final EncryptorManager encryptorManager;

    /**
     * 出参解密
     *
     * @param invocation 被拦截方法的详细信息
     * @return 拦截处理后方法的返回值
     * @throws Throwable 被拦截方法运行出现异常抛出此异常
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();

        if (result instanceof List<?> list && CollUtil.isNotEmpty(list)) {
            try {
                encryptorManager.handleFields(list.get(0), DECRYPT);
            } catch (IllegalAccessException e) {
                log.error("解密敏感字段时出错", e);
            }
        }

        return result;
    }
}
